package com.scau.database.service.stockbuyer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.scau.data.entity.CommodityInfoDO;
import com.scau.data.entity.FactoryDO;
import com.scau.data.entity.OrderDO;
import com.scau.data.entity.OrderLineDO;
import com.scau.database.common.service.ImportMapperService;
import com.scau.database.entity.stockbuyer.*;
import com.scau.database.utils.WordBuidUtil;
import com.scau.database.utils.entity.OrderInWordTableVO;
import freemarker.template.TemplateException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class StockBuyerService {
    final static Integer HAS_NOT_NUMBER = -1; // 解析的字符串不含有ID数字
    // 进货单名称
    private static final String ORDER_TITLE = "知己电子连锁商城进货单";
    private static final String BUYER = "知己电子有限公司";
    // WORD 模板
    private static final String WORD_TEMPLATE_NAME = "order.ftl";
    @Autowired
    private WordBuidUtil wordBuidUtil;
    @Autowired
    private ImportMapperService importMapperService;

    /**
     * 获取工厂
     * @return
     */
    public List<FactoryVO> getFactorys(){
        return importMapperService.factoryMapper.getFactorys();
    }

    /**
     * 获取仓库
     * @return
     */
    public List<WarehouseVO> getWarehouse(){
        return importMapperService.wareHouseMapper.getWarehourses();
    }

    /**
     * 搜索商品
     * @param index
     * @return
     */
    public List<SearchCommodityVO> getSearchCommodities(String index){
        String qureyIndex = "%" + index + "%";
        return importMapperService.commodityInfoMapper.getSearchCommodities(qureyIndex);
    }
    private Integer parseFW(String s){
        String[] split = s.split("-");
        if (split.length < 1){
            return HAS_NOT_NUMBER;
        }
        String numberStr = split[0];
        Integer ret = null;
        try{
             ret = Integer.valueOf(numberStr);
        }catch (NumberFormatException e){
            ret = HAS_NOT_NUMBER;
        }
        return ret;
    }
    /**
     * 创建订单
     * factory、warehouse是  [id]-[name] 格式的字符串，需要额外解析
     * @param createDTO
     * @return
     */
    @Transactional
    public CreateResultDTO createOrder(CreateDTO createDTO){
        CreateResultDTO createResultDTO = new CreateResultDTO();

        boolean needPrint = createDTO.getNeedPrint();
        String factory = createDTO.getFactory();
        String payMethod = createDTO.getPayMethod();
        String warehouse = createDTO.getWarehouse();
        List<OrderDTO> orders = createDTO.getOrders();

        Integer factoryId = parseFW(factory); // 工厂ID
        Integer warehouseId = parseFW(warehouse); // 仓库ID
        BigDecimal amount = orders.stream()  // 计算总价
                .map(OrderDTO::getSumaryPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 以下是订单头信息
        OrderDO orderDO = new OrderDO();
        orderDO.setTime(new Date());
        orderDO.setFactoryId(factoryId);
        orderDO.setPayMethod(payMethod);
        orderDO.setWarehouseId(warehouseId);
        orderDO.setAmount(amount);

        int insertOrder = importMapperService.orderMapper.insert(orderDO); // 写入数据库
        Long orderNumber = orderDO.getOrderNumber();

        Iterator<OrderDTO> iterator = orders.iterator();
        while (iterator.hasNext()){
            OrderDTO next = iterator.next();
            // 创建DO对象
            OrderLineDO orderLineDO = new OrderLineDO();
            orderLineDO.setOrderNumber(orderNumber);
            orderLineDO.setBarCode(next.getBar_code());
            orderLineDO.setBrand(next.getBrand());
            orderLineDO.setCommodity(next.getCommodity());
            orderLineDO.setCount(next.getCount());
            orderLineDO.setExplain(next.getExplain());
            orderLineDO.setIndex(next.getIndex());
            orderLineDO.setRepairDays(next.getRepair_days());
            orderLineDO.setReturnDays(next.getReturn_days());
            orderLineDO.setExchangeDays(next.getExchange_days());
            orderLineDO.setUnitPrice(next.getUnit_price());

            // 保存DO对象
            int insert = importMapperService.orderLineMapper.insert(orderLineDO);

            // 更新commodity_info 表
            updateCommodityInfo(orderLineDO,next);
        }
        createResultDTO.setOrderNumber(orderNumber);
        createResultDTO.setStatus(1);
        return createResultDTO;
    }

    /**
     *   // 查询commodity_info表，是否存在该记录
     *             // 若存在
     *             //      更新信息
     *             // 若不存在
     *             //      创建新的记录
     * @param orderLineDO
     * @return
     */
    public Integer updateCommodityInfo(OrderLineDO orderLineDO,OrderDTO orderDTO){
        String barCode = orderLineDO.getBarCode();
//        CommodityInfoDO commodityInfoDO = new CommodityInfoDO();
//        commodityInfoDO.setBarCode();
        List<CommodityInfoDO> commodityInfoByBarCode = importMapperService.commodityInfoMapper.getCommodityInfoByBarCode(barCode);
        CommodityInfoDO commodityInfoDO = new CommodityInfoDO();

        BeanUtils.copyProperties(orderLineDO,commodityInfoDO); // 进行属性赋值
        commodityInfoDO.setName(orderLineDO.getCommodity());
        commodityInfoDO.setRecommendPrice(orderDTO.getRecommend_price());
        commodityInfoDO.setMaxPrice(orderDTO.getMax_price());
        commodityInfoDO.setMinPrice(orderDTO.getMin_price());
        commodityInfoDO.setLimitBuy(orderDTO.getLimit_buy());

        if (commodityInfoByBarCode.isEmpty()){
            // 如果还没有记录的话
            importMapperService.commodityInfoMapper.insert(commodityInfoDO);
        }else {
            importMapperService.commodityInfoMapper.update(commodityInfoDO,new UpdateWrapper<CommodityInfoDO>()
            .eq("bar_code",commodityInfoDO.getBarCode()));
        }
        return 1;
    }

    /**
     * 生成Word订货单，并通过httpServletResponse输出到浏览器
     * @param response
     * @param orderNumber
     */
    public void buildWordOrder(HttpServletResponse response, Long orderNumber) throws IOException, TemplateException {
        Map<String, Object> dataMap = getWordDataMap(orderNumber);
        String fileName = orderNumber.toString() + "订货单";
        wordBuidUtil.renderingWordModel2HTTP(response,WORD_TEMPLATE_NAME,dataMap,fileName);
    }

    /**
     * 封装dataMap
     * @param orderNumber
     * @return
     */
    private Map<String,Object> getWordDataMap(Long orderNumber){
        Map<String, Object> map = new HashMap<>();

        QueryWrapper<OrderDO> orderDOQueryWrapper = new QueryWrapper<>();
        orderDOQueryWrapper.eq("order_number",orderNumber);
        OrderDO orderDO = importMapperService.orderMapper.selectOne(orderDOQueryWrapper);
        if (orderDO == null)return null;

        QueryWrapper<OrderLineDO> orderLineDOQueryWrapper = new QueryWrapper<>();
        orderLineDOQueryWrapper.eq("order_number",orderNumber);
        List<OrderLineDO> orderLineDOS = importMapperService.orderLineMapper.selectList(orderLineDOQueryWrapper);

        // 表头信息封装
        map.put("title",ORDER_TITLE);
        map.put("id",orderNumber);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = simpleDateFormat.format(orderDO.getTime());
        map.put("date",date);
        map.put("buyer",BUYER);
        Integer factoryId = orderDO.getFactoryId();
        QueryWrapper<FactoryDO> factoryDOQueryWrapper = new QueryWrapper<>();
        factoryDOQueryWrapper.eq("id",factoryId);
        FactoryDO factoryDO = importMapperService.factoryMapper.selectOne(factoryDOQueryWrapper);
        String seller = " ";
        String address = " ";
        if (factoryDO != null){seller = factoryDO.getName();address = factoryDO.getAddress();}
        map.put("seller",seller);
        map.put("address",address);
        map.put("pay",orderDO.getPayMethod());

        // 订单信息封装
        List<OrderInWordTableVO> orderList = new ArrayList<>();
        Iterator<OrderLineDO> iterator = orderLineDOS.iterator();
        while (iterator.hasNext()){
            OrderLineDO next = iterator.next();
            OrderInWordTableVO order = new OrderInWordTableVO();
            order.setOne(next.getIndex());
            order.setT(next.getCommodity());
            order.setTh(next.getBarCode());
            order.setFo(next.getUnitPrice());
            order.setFi(next.getCount());
            order.setSi(next.getExchangeDays());
            order.setSe(next.getRepairDays());
            order.setEh(next.getReturnDays());

            orderList.add(order);
        }
        map.put("orderList",orderList);
        return map;
    }
}